<?php
namespace My\EhrBundle\Lib;
use Symfony\Component\HttpFoundation\Request;

class Pagination {
    private $_pager = null;
	private $_query = null;
	private $_queryString = '';
	
    public function __construct( Pager $pager )
    {
        $this->_pager = $pager;
		$this->_default_query = Request::createFromGlobals()->query;
        $this->_initialize();
    }
    private function _initialize()
    {
		$this->_query = clone $this->_default_query;
    }
	private function getQueryString()
	{
		$queryString = array();
		
		foreach( $this->_query->all() as $k => $v)
		{
			$queryString[] = "{$k}={$v}";			
		}
		
		return join( '&', $queryString );
	}
    public function getDqlOrderBy( $fieldMaps )
    {
		if( $this->_default_query->get('orderby', false) )
		{
			$keyToOrder = $this->_default_query->get('orderby');
			
			$order = "asc";
			
			if( $this->_default_query->get('order', false)  )
			{
				$i_order = $this->_default_query->get('order');
				
				if( preg_match('/^asc|desc$/', $i_order) )
				{
					$order = $i_order;
				}	
			}
			
			if( isset( $fieldMaps[$keyToOrder] ) )
			{
				return sprintf( " ORDER BY %s %s ", $fieldMaps[$keyToOrder], strtoupper($order) );
			}
		}
		return "";
    }

	public function __call( $magicMethod, $arguments )
	{
		if( preg_match( '/^query(?<page>First|Next|Previous|Last)$/',$magicMethod, $match) )
		{
			$this->_query->set( 'page', $this->_pager->{sprintf("get%sPage",$match['page'])}() );
		}
		else if( preg_match( '/^query(?<method>[a-zA-Z0-9]+)_(?<arg>[a-zA-Z0-9_]+)$/',$magicMethod, $match) )
		{
			$this->_initialize();
			
			if( $match['method'] === 'OrderBy' )
			{
				if( $this->_query->get('orderby') === $match['arg'] )
				{
					if( $this->_query->get( 'order' ) === 'asc' )
					{
						$this->_query->set( 'order', 'desc' );
					}
					else
					{
						$this->_query->set( 'order', 'asc' );
					}
				}
				else
				{
					$this->_query->set( 'order', 'asc' );
				}
				$this->_query->set('orderby', $match['arg'] );
			}
		}
		return $this->getQueryString();
	}
}
?>
